package com.example.math;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.util.Log;

public class SecondScreenListParser {

	private static final String tag = "itemParser";
	private static final String FILE_EXTENSION= ".png";
	
	private DocumentBuilderFactory factory;
	private DocumentBuilder builder;
	private final HashMap<String, String> map;
	private final List<SecondScreenListClass> list;

	public SecondScreenListParser() {
		this.list = new ArrayList<SecondScreenListClass>();
		this.map = new HashMap<String, String>();
	}

	private String getNodeValue(NamedNodeMap map, String key) {
		String nodeValue = null;
		Node node = map.getNamedItem(key);
		if (node != null) {
			nodeValue = node.getNodeValue();
		}
		return nodeValue;
	}

	public List<SecondScreenListClass> getList() {
		return this.list;
	}


	/**
	 * Parse XML file containing body part X/Y/Description
	 * 
	 * @param inStream
	 */
	public void parse(InputStream inStream) {
		try {
			// TODO: after we must do a cache of this XML!!!!
			this.factory = DocumentBuilderFactory.newInstance();
			this.builder = this.factory.newDocumentBuilder();
			this.builder.isValidating();
			Document doc = this.builder.parse(inStream, null);

			doc.getDocumentElement().normalize();

			NodeList itemList = doc.getElementsByTagName("item");
			final int length = itemList.getLength();

			for (int i = 0; i < length; i++) {
				final NamedNodeMap attr = itemList.item(i).getAttributes();
				final String name = getNodeValue(attr, "name");
				final String imageFile = getNodeValue(attr, "img");

				// Construct item object
				SecondScreenListClass itemObject = new SecondScreenListClass(name, imageFile,
						 imageFile + FILE_EXTENSION);
				
				// Add to list
				this.list.add(itemObject);
				
				// Creat Map itemname-imageFile
				this.map.put(name, imageFile);
				Log.d(tag, itemObject.toString());
			}
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
	}
}
